package main

import (
	"fmt"
	"os"
	"sort"

	//"github.com/ngaut/log"
)

// https://blog.golang.org/maps
// 用对map 用range loop时， 不能保证迭代顺序 ，若想稳定迭代，可以弄个slice key，sort the slice，然后按照slice key来访问map

//https://www.kancloud.cn/liupengjie/go/574260
func t_map() {
	m := map[string]string{"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"}
	fmt.Println("testing map loop and its iteration order is undefined")
	for k, v := range m {
		fmt.Println(k, v)
	}

	if _, ok := m["k1"]; !ok {
		fmt.Println("ok=", ok)
	}
	os.Exit(0)

	for k := range m {
		fmt.Fprintf(os.Stdout, "%s ", m[k])
	}

	// lookup
	value, ok := m["k4"]
	if ok {
		fmt.Println("found k4:", value)
	}

	delete(m, "k5") //delete is no-op if m =nil or key not existed

	sliceOfMap := func() {
		items := make([]map[int]int, 5)
		for i := 0; i < 5; i++ {
			items[i] = make(map[int]int)
		}
		items[0][0] = 0 //0,0是键值对
		items[1][2] = 3 // 2,3是键值对
		fmt.Println(items)
	}
	sliceOfMap()

	sortMap := func() {
		m := map[string]string{"q": "q", "w": "w", "e": "e", "r": "r", "t": "t", "y": "y"}
		var slice []string
		for k, _ := range m {
			slice = append(slice, k)
		}
		// 先收集所有的Key,然后按照Key来遍历map
		fmt.Printf("map's key is : %v\n", slice)
		sort.Strings(slice[:])
		fmt.Printf("sorted slice string is : %v\n", slice)
		for _, v := range slice {
			fmt.Println(m[v])
		}
	}
	sortMap()

	var m2 map[string]string
	m2 = make(map[string]string) // 必须 make，否则nil map不可以被赋值
	m2["a"] = "a"
	fmt.Println(m2)

	var m3 = map[int]int{}
	println("m3 addr :", m3)
	fmt.Println("m3:", m3)

	var m4 = make(map[int]int)
	fmt.Println("m4:", m4)

	type my struct {
		x string
		y int
	}
	strint := []my{{"a", 1}, {"b", 2}, {"a", 3}, {"b", 4}, {"c", 5}}
	sum := map[string]int{}
	for _, i := range strint {
		sum[i.x] += i.y
	}
	fmt.Println(sum)
}
